<?php

namespace App\Http\Controllers\System;


use App\Model\System\Eeofile;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Http\Controllers\MessagePacket;
use function PHPSTORM_META\elementType;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\Exception\FileException;


class FileController extends BaseController
{
    use MessagePacket;


    function  __construct(){}


    /**
     * 文件上传
     * @param Request $request
     * @return array
     */
    function  uploadFile(Request $request)
    {
        $name = 'Filedata';
        if($request->hasFile($name)){
            $file = $request->file($name);
        }else{
            return $this->fail(null, '文件字段错误');
        }

        $move2path = $this->makeUploadPath($file);
        $existedFile = $this->getUploadFileFullName($file);
        if(file_exists($existedFile)){
            return $this->success($this->getPublicPath($existedFile));
        }

        try{
            $target = $file->move($move2path, md5(time() . mt_rand(1,1000000)).'.'.$file->extension());
            return $this->success($this->getPublicPath($target->getRealPath()));
        }catch (FileException $exception){
            return $this->fail(null,'上传失败:'.$exception->getMessage());
        }
    }


    /**
     * 通过php返回文件内容
     * @param Request $request
     */
    function getFile(Request $request)
    {
        #http://localhost:8888/api/file?u=image/2e/82/q.jpg
        $path = $this->getPublicRealPath($request->u);
        $file = new File($path);
        header("Content-type: ".$file->getMimeType());
        echo file_get_contents($path);
        exit;
    }


    /**
     * 计算文件存放目录
     * @param $file
     * @return string
     */
    protected function makeUploadPath($file)
    {
        static $path=null;

        if(is_null($path)){
            $type = 'unfound';
            if($types = explode('/',$file->getMimeType())){
                $type = $types[0];
            }
            $hash = md5_file($file->getRealPath());
            $first = substr($hash,0,2);
            $second = substr($hash,-2);
            $path = $this->baseDir() . "$type/$first/$second/";
        }
        return $path;
    }


    /**
     * 计算目标文件
     * @param $file
     * @return string
     */
    protected function getUploadFileFullName($file)
    {
        return $this->makeUploadPath($file) . $file->getClientOriginalName();
    }


    /**
     * 获取文件的web访问目录
     * @param $fullPath
     * @return mixed
     */
    protected function getPublicPath($fullPath)
    {
        $base = $this->baseDir();
        $fullPath = str_ireplace('\\','/', $fullPath);
        $dir = str_replace($base, '', $fullPath);
        return $dir;
    }


    /**
     * 获取文件的服务端存储目录
     * @param $path
     * @return string
     */
    protected function getPublicRealPath($path)
    {
        return  $this->baseDir() . $path;
    }


    /**
     * 获取文件存储的一级目录
     * @return mixed|string
     */
    protected function baseDir()
    {
        $envDir = env('APP_UPLOAD_PATH');
        if($envDir[0]=='.'){
            $envDir = str_replace('.', '', $envDir);
            $base = dirname($_SERVER['DOCUMENT_ROOT']) . $envDir;
        }else{
            $base = $envDir;
        }
        $base = str_ireplace('\\','/', $base);
        return $base;
    }

    /**
     * 裁剪图片
     * @param Request $request
     * @return array
     * @throws \Exception
     *
     */
    function imageCrop(Request $request)
    {
        try{
            if($request->has(['filefullpath','x','y','w','h']))
            {

                $targ_w =$request->get('w');
                $targ_h =$request->get('h');
                $file = $request->get('filefullpath');
                $file = explode('=',$file);
                $temp = $file[1];
                $file = Eeofile::getLocalPath($file[1]);
                list($width, $height, $image_type) = getimagesize($file);

                $name = explode('.',$temp);
                $new_name = $name[0].'_crop.'.$name[1];
                $new_file = Eeofile::getLocalPath($new_name);
                switch ($image_type)
                {
                    case 1: $src = imagecreatefromgif($file); break;
                    case 2: $src = imagecreatefromjpeg($file);  break;
                    case 3: $src = imagecreatefrompng($file); break;
                    default: return $this->fail('未识别的图片类型');  break;
                }

                $im2 = imagecrop($src, ['x' => $_POST['x'], 'y' => $_POST['y'], 'width' => $targ_w, 'height' => $targ_h]);
                if ($im2 !== FALSE) {
                    switch ($image_type)
                    {
                        case 1: imagegif($im2, $new_file); break;
                        case 2: imagejpeg($im2, $new_file); break;
                        case 3: imagepng($im2, $new_file); break;
                        default: break;
                    }

                }
                return $this->success($new_name);
            }else{
                return $this->fail(false,'请求参数不全');
            }
        }catch (\Exception $e){
            return $this->fail(false,"裁剪失败：".$e->getMessage());
        }
    }

}
